package com.gykfbxxh.imovie.view.lunch;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.utils.util.StringUtils;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.base.bean.DataBean;
import com.gykfbxxh.imovie.bean.config.ChannelItem;
import com.gykfbxxh.imovie.bean.config.ConfigScreenBean;
import com.gykfbxxh.imovie.bean.config.OpenBean;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.manager.AppChannelManager;
import com.gykfbxxh.imovie.manager.AppConfigManager;
import com.gykfbxxh.imovie.utils.HttpUtils;
import com.gykfbxxh.imovie.utils.glide.ImageLoader;
import com.gykfbxxh.imovie.view.main.MainActivity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xuxinghai
 * On 2017/8/17
 * 软件启动页面
 */

public class LunchActivity extends Activity {
    /**************
     * 页面控件
     *****************/

    private ImageView appstartimg;
    private View bottomLayout;//底部横幅
    private FrameLayout topLayout;//上部容器
    private TextView skipView;//跳过
    private View skipProgess;

    /**************页面控件*****************/

    /********************
     * 逻辑数据
     ***************/

    private boolean isAdLoad;//是否加载广告
    private boolean isAdTiaozhuan;//是否跳转广告
    private Timer timer;//跳过计时器
    private int adTime = 3;//进入主页面计时时间,默认3秒
    private boolean isBotomShow;//是否显示底部

    private String mPageName = "LunchActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        boolean isNoWolcome = AppConfigManager.getInstance().getConfigSP().getBoolean(ConfigKey.isStartWelcome, false);
        setContentView(R.layout.activity_lunch);
        if(!isNoWolcome) {
            Intent intent = new Intent(this, Welcome.class);
            startActivity(intent);
            finish();
            return;
        }
        // 初始化控件
        initView();
        //拉取整体样式显示
        configOpen();
        // 拉取服务器开屏配置
        configScreenImg();
        //配置片库栏目列表
        checkUpdateChannel();
        // 跳转主界面
        redirectToMain();
    }

    /**
     * 拉取整体样式显示
     */
    private void configOpen() {
//        if(1==1) {
//            AppConfigManager.getInstance().getEditor().putBoolean(ConfigKey.beginsStyle,true).commit();
//            return;
//        }
        HttpUtils.addGetRequest(URIContant.GETOPEN, new TypeToken<OpenBean>() {
        }.getType(), mPageName, new HttpListener<OpenBean>() {
            @Override
            public void onError(VolleyError error) {

                AppConfigManager.getInstance().getEditor().putBoolean(ConfigKey.beginsStyle,false).commit();
            }

            @Override
            public void onSuccess(OpenBean response) {
                if(response!=null && response.noError()) {
                    OpenBean.OpenData openData = response.getResult();
                    if(openData!=null) {
                        if(0==openData.getShowType()) {
                            AppConfigManager.getInstance().getEditor().putBoolean(ConfigKey.beginsStyle,false).commit();
                        }else {
                            AppConfigManager.getInstance().getEditor().putBoolean(ConfigKey.beginsStyle,true).commit();
                        }
                    }else {
                        AppConfigManager.getInstance().getEditor().putBoolean(ConfigKey.beginsStyle,false).commit();
                    }
                }else {
                    AppConfigManager.getInstance().getEditor().putBoolean(ConfigKey.beginsStyle,false).commit();
                }
            }
        });
    }


    /**
     * 初始化控件
     */
    private void initView() {
        this.appstartimg = (ImageView) findViewById(R.id.app_start_img);
        this.bottomLayout = findViewById(R.id.bottom_img_layout);
        this.topLayout = (FrameLayout) findViewById(R.id.start_img_layout);
        skipProgess = findViewById(R.id.pb_loading_progress);
        this.skipView = (TextView) findViewById(R.id.tv_tiaoguo);

        skipView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (skipView != null) {
                    skipView.setVisibility(View.GONE);
                }
                if (skipProgess != null) {
                    skipProgess.setVisibility(View.VISIBLE);
                }
                isAdTiaozhuan = true;
                redirectToActivity();
            }
        });
    }

    /**
     * 跳转主界面
     */
    private void redirectToMain() {
        // adTime秒后启动主页面
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                //如果跳转过广告则不再执行跳转主页面
                if (isAdTiaozhuan) {
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    return;
                }
                adTime--;
                skipView.setText(Html.fromHtml("跳过\n" + "<font color='#E55D5D'>" + adTime + "</font>" + "s"));
                if (adTime <= 0) {
                    //退出循环
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    //跳转页面
                    redirectToActivity();
                }
            }
        };
        timer = new Timer();
        //每隔1s就执行一次
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        }, 1000, 1000);
    }


    /**
     * 跳转页面
     */
    private void redirectToActivity(){

        Intent intent = getIntent();
        boolean isToMain = true;
//        if(intent != null){
//            String id = intent.getStringExtra(BaseActivity.PARAMETER1);
//            if(!TextUtils.isEmpty(id)){
//                String type = intent.getStringExtra(BaseActivity.PARAMETER2);
//                NewsEntity newsEntity = new NewsEntity();
//                newsEntity.setArticleId(id);
//                newsEntity.setArticleType(type);
//                isToMain =  !TypeConstant.openTypeDetail(newsEntity, this, intent.getStringExtra(TypeConstant.PUSH_TYPE));
//            }
//
//        }

        //如果跳转了内页则不再跳转主页面
        if(isToMain){
            startActivity(new Intent(LunchActivity.this, MainActivity.class));
            overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
            finish();
        }else{
            finish();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }


    /**
     * 拉去开屏配置
     */
    private void configScreenImg() {
        HttpUtils.addGetRequest(URIContant.GETCONFIGIMG, new TypeToken<ConfigScreenBean>() {
        }.getType(), mPageName, new HttpListener<ConfigScreenBean>() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(ConfigScreenBean response) {
                if(response!=null&&response.getResult()!=null) {
                    ConfigScreenBean.ConfigScreen configScreen = response.getResult();
                    String time = configScreen.getTime();
                    if(!TextUtils.isEmpty(time)&&!TextUtils.isEmpty(configScreen.getImg())&&!TextUtils.isEmpty(configScreen.getUrl())) {
                        adTime = StringUtils.toInt(time, 3);
                        ImageLoader.getInstance().loadSmallImage2Cache(LunchActivity.this,appstartimg,configScreen.getImg());
                        appstartimg.setTag(R.id.tag_first,configScreen.getUrl());
                        appstartimg.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String url = (String) v.getTag(R.id.tag_first);
                                if(!TextUtils.isEmpty(url)) {
                                    Intent intent = new Intent();
                                    intent.setAction("android.intent.action.VIEW");
                                    Uri content_url = Uri.parse(url);
                                    intent.setData(content_url);
                                    try {
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                        skipView.setVisibility(View.VISIBLE);
                    }

                }
            }
        });
    }

    /**
     * 检查更新服务器配置所有栏目列表
     */
    private void checkUpdateChannel() {

        //更新栏目
        HttpListener<DataBean<ChannelItem>> httpListener = new HttpListener<DataBean<ChannelItem>>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean<ChannelItem> response) {
                if (response.noError()) {
                    List<ChannelItem> channelOnlineList = response.getResult();

                    if (channelOnlineList == null || channelOnlineList.size() == 0) {
                        return;
                    }
                    //更新本地栏目数据
                    AppChannelManager.getInstance().updateServicesChannel(channelOnlineList);
                    //如果本地缓存成功则 记录更新时间

                }

            }
        };
        HttpUtils.addGetRequest(URIContant.GETCHANNEL, new TypeToken<DataBean<ChannelItem>>() {
        }.getType(), mPageName, httpListener);

    }

}
